package uk.co.douglashoskins.weathercompare.providers;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.Image;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import uk.co.douglashoskins.weathercompare.WeatherCompare;
import uk.co.douglashoskins.weathercompare.controller.WeatherObj;
import uk.co.douglashoskins.weathercompare.controller.WeatherObj.WeatherSummary;
import uk.co.douglashoskins.weathercompare.services.NetQueueCallback;
import uk.co.douglashoskins.weathercompare.util.Weather;

public class Google implements WeatherProvider, NetQueueCallback {
	private WeatherCallback wc;
	
	private String fix(double coord) {
		String latStr = Double.toString(coord);
		int dot = latStr.indexOf('.');
		String dotless = latStr.substring(0, dot) + latStr.substring(dot + 1);
		while(dotless.length() < 9)
			dotless = dotless.concat("0");
	    if(dotless.indexOf('-') != -1)
	    	dotless = dotless.substring(0,9);
	    else
	    	dotless = dotless.substring(0,8);
	    System.out.println(coord + " fixed is " + dotless);
	    return dotless;
	}
	
	public void getWeather(double lat, double lng, WeatherCallback wc) {
		this.wc = wc;
		
		//String yql = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20%22http%3A%2F%2Fwww.google.com%2Fig%2Fapi%3Fweather%3D%2C%2C%2C" + fix(lat) + "%2C" + fix(lng) + "%22&format=json";
		String url = "http://www.google.com/ig/api?weather=,,," + fix(lat) + "," + fix(lng);
		WeatherCompare.n.addRequest(url, this);
	}

	public Image logo() { return null; }
	public String name() { return "Google"; }

	private int getCode(String condition) {
		condition = condition.toLowerCase();
		if (condition.indexOf("storm") != -1) {
			return Weather.THUNDERSTORM;
		}
		if (condition.indexOf("snow") != -1 || condition.indexOf("sleet") != -1) {
			return Weather.SNOW;
		}
		if (condition.indexOf("intervals") != -1) {
			return Weather.SUNNY_INTERVALS;
		}
		if (condition.indexOf("showers") != -1 || condition.indexOf("rain") != -1) {
			return Weather.RAIN;
		}
		if (condition.indexOf("fog") != -1 || condition.indexOf("mist") != -1) {
			return Weather.FOG;
		}
		if (condition.indexOf("sun") != -1 || condition.indexOf("clear") != -1) {
			return Weather.SUN;
		}
		return Weather.CLOUD;
	}
	
	private void populateSummary(JSONObject forecast, WeatherSummary ws) throws JSONException {
		ws.low = Weather.toCels(forecast.getJSONObject("low").getInt("data"));
		ws.high = Weather.toCels(forecast.getJSONObject("high").getInt("data"));
		ws.text = forecast.getJSONObject("condition").getString("data");
		ws.code = getCode(ws.text);
	}
	
	public void netCallback(final String s) throws IOException {
		//try {
			/*JSONObject j = new JSONObject(s);
			JSONObject results = j.getJSONObject("query").getJSONObject("results");
			JSONArray forecasts = results.getJSONObject("xml_api_reply").getJSONObject("weather").getJSONArray("forecast_conditions");
			WeatherObj wo = new WeatherObj();
			populateSummary(forecasts.getJSONObject(0), wo.today);
			populateSummary(forecasts.getJSONObject(1), wo.tomorrow);
			wc.weatherCB(wo, this);*/
			try {
				
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				sp.parse(new InputStream() {
					private int count = 0;
					public int read() throws IOException {
						if (count < s.length()) {
							return (int)s.charAt(count++);
						}
						return -1;
					}
				}, new DefaultHandler() {
					public void startElement(java.lang.String uri, java.lang.String localName, java.lang.String qName, Attributes attributes) {
						System.out.println("uri: " + uri);
						System.out.println("localName: " + localName);
						System.out.println("qName: " + qName);
					}
				});
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			
		//} catch (JSONException e) {
		//	e.printStackTrace();
		//}
	}

	public void netException(Exception exc) {

	}
}
